package com.itheima.flters;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.Object;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Slf4j
public class ApAuthFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取Request和Response请求体
        ServerHttpResponse resp = exchange.getResponse();
        ServerHttpRequest req = exchange.getRequest();
        //获取请求路径，判断是否是登录请求，是则直接放行
        String path = req.getURI().getPath();
        //判断路径是否包含login，是则直接放行
        if (path.contains("/login/login_auth")){
            return chain.filter(exchange);
        }
        //获取请token求头
        String token = req.getHeaders().getFirst("token");
        //判断请求头是否有值，为空则抛出异常
        if (StringUtils.isEmpty(token)){
            throw new LeadNewsException("权限不足请先登录！");
        }
        //token有值则进行token校验
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims != null) {
                //获取载荷上的userId
                String id = claims.getId();
                //将获取到的userId存入请求头中,因为网关微服务与用户微服务的服务器不一致，所以需要转换mutate()
                req.mutate().header("userId",id);
                //更据token获取载荷，有值则表示有效，放行
                return chain.filter(exchange);
            }
        } catch (ExpiredJwtException ex) {
            //进入这里表示token超时，抛出异常
            log.info("该用户登录的token超时了");
            throw new LeadNewsException("权限不足请先登录!");
        } catch (Exception e) {
            log.error("权限不足,非法token",e);
            throw new LeadNewsException("权限不足请先登录!");
        }
        //拦截请求响应状态码
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        return resp.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
